<!-- 聊天编辑区域 -->
<template>
  <div class="chat-editor-container">
    <div class="base">
      <div class="left-icon">
        <van-icon class="iconfont"
                  class-prefix="icon-ali"
                  :name="isText ? 'jianpan' : 'yuyin'"
                  size="26"
                  @click="toggle" />
      </div>

      <div id="contentDiv"
           v-show="isText"
           class="textarea content-text"
           :class="chatContent ? 'div-button-style' : 'div-icon-style'"
           contenteditable="true"
           tabindex="0"
           @input="changeInput"
           placeholder="请输入聊天内容"
           v-on:keyup="contentChange"
           ref="chatContentDom"
           v-on:blur="withdrawKeyBoard"
           v-on:focus="popKeyBoard"></div>
      <!-- 语音录制按钮 -->
      <van-button class="record-btn"
                  @touchstart="touchstart"
                  @touchend="touchend"
                  @touchmove="touchmove"
                  @touchmove.prevent
                  v-show="!isText">
        {{ btRecoding ? "松开 结束" : "按住 说话" }}
      </van-button>

      <!-- 语音录制弹框 -->
      <div class="shade"
           v-if="btRecoding"
           catchtouchmove="true">
        <div class="blackBoxSpeak"
             v-if="blackBoxSpeak">
          <div>
            <img src="../static/ic_record.gif" />
          </div>
          <div class="blackBoxSpeakConent">手指上划，取消录制</div>
        </div>
        <div class="blackBoxPause"
             v-else>
          <img src="../static/ic_release_to_cancel.png" />
          <div class="blackBoxSpeakConent"
               style="background: red">
            松开手指，取消录制
          </div>
        </div>
      </div>

      <div class="right-icon">
        <div class="right-icon-emoij">
          <van-icon name="smile-o"
                    size="26"
                    @click="toggleShowEmoji" />
        </div>

        <div :class="chatContent !== '' && chatContent != undefined ? 'right-icon-add-none' : 'right-icon-add'">
          <van-button type="success"
                      size="small"
                      v-if="chatContent && isText"
                      class="send-btn"
                      @click="sendChatMsg">发送</van-button>
          <van-icon id="cameraPopupId"
                    @click.stop="toggleShowCameraPopup"
                    name="add-o"
                    size="26"
                    v-else />
        </div>
      </div>
    </div>

    <!-- 相机/文件图片等弹框 -->
    <div class="cameraPopup"
         v-show="showCamera">

      <div v-if="!showEmoji"
           class="grid-input-style"
           v-for="(value, index) in cameraPopupContent"
           :key="index">
        <div class="icon-input"
             :style="{backgroundImage:'url('+value.icon+')'}">
          <input :type="value.type"
                 @change="uploadFile"
                 multiple="multiple"
                 :accept="value.accept"
                 :capture="value.capture"
                 class="input-btn-style"
                 v-if="value.type === 'file'" />
          <input :type="value.type"
                 @click="callYuyin"
                 class="input-btn-style"
                 v-else-if="value.type === 'button' && value.name === 'yuyin'" />
          <input :type="value.type"
                 @click="callShipin"
                 class="input-btn-style"
                 v-else-if="value.type === 'button' && value.name === 'shipin'" />
          <input :type="value.type"
                 @click="callHongbao"
                 class="input-btn-style"
                 v-else-if="value.type === 'button' && value.name === 'hongbao'" />
        </div>
        <div class="icon-text">{{value.text}}</div>

      </div>

      <!-- 表情弹框 -->
      <div v-else>我是表情</div>

    </div>

    <!-- 遮罩层 -->
    <div class="yuyin-container">
      <van-overlay :show="showOverlay"
                   duration="0.5">
        <div class="yuyin-wrapper"
             @click.stop>

          <!-- 头部区域 -->
          <div class="yuyin-head">
            <van-row>
              <van-col span="4">
                <van-icon class="iconfont"
                          class-prefix="icon-ali"
                          name="suoxiao"
                          size="20" />
              </van-col>
              <van-col span="10"
                       offset="4">等待对方接受邀请...</van-col>
            </van-row>

          </div>
          <!-- 中间body -->
          <div class="yuyin-body">
            <div class="user-avater-style">
              <van-image width="100"
                         height="100"
                         radius="20"
                         src="https://img.yzcdn.cn/vant/cat.jpeg" />
            </div>
            <div class="user-name-style">
              <sapn>孤独的狼</sapn>
            </div>

          </div>
          <!-- 脚部区域 -->
          <!-- 发起方 -->
          <div class="yuyin-foot"
               v-if="isCaller">
            <div class="maikefeng">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="mic-on"
                        size="26" />
            </div>
            <div class="dianhua">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="dianhuaguaduan"
                        @click="hungup"
                        size="26" />
            </div>
            <div class="yangshengqi">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="closeyangshengqi"
                        size="26" />
            </div>
          </div>

          <!-- 接收方callee -->
          <div class="yuyin-foot"
               v-else>
            <div class="dianhua">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="dianhuaguaduan"
                        @click="hungup"
                        size="26" />
            </div>
            <div class="yangshengqi">
              <van-icon class="iconfont"
                        class-prefix="icon-ali"
                        name="dianhua"
                        @click="answering"
                        size="26" />
            </div>
          </div>
        </div>
      </van-overlay>
    </div>

  </div>
</template>

<script>
import { Toast } from 'vant';
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  props: {
    to: {
      type: String,
      default () {
        return ''
      },
    },
    isCaller0: {
      type: Boolean,
      default () {
        return true
      },
    },
    showOverlay0: {
      type: Boolean,
      default () {
        return false
      },
    },
    singleType: {
      type: String,
      default () {
        return ""
      },
    }
  },
  components: {},
  data () {
    //这里存放数据
    return {
      // 音视频发起者
      isCaller: this.isCaller0,
      // webrtc 对象
      webrtc: null,
      // 录音对象
      recorder: null,
      // 展示遮罩层
      showOverlay: this.showOverlay0,
      // 视频遮罩层
      showShipinOverlay: false,
      // div编辑框光标初始位置
      cursor: 0,
      // 聊天内容可以是html
      chatContent: "",
      isText: true,
      // 控制录音弹框
      loop: '',
      btRecoding: false,
      blackBoxSpeak: false,
      startY: 0,
      recordPeriodTime: 0,
      delayTime: '',
      // 大于60秒会设置为true
      endEarly: false,
      // 控制相机，文件，视频等功能的弹窗
      showCamera: false,
      // 展示表情弹框
      showEmoji: false,

      // 更多相机的内容
      cameraPopupContent: [
        {
          type: "file",
          icon: require('../static/pic/xiangce.png'),
          accept: "image/jpeg,image/png,image/gif",
          text: "相册",
        },
        {
          type: "file",
          icon: require('../static/pic/paizhao.png'),
          accept: "image/*",
          capture: "camera",
          text: "拍照",
        },
        {
          type: "file",
          icon: require('../static/pic/luxiang.png'),
          accept: "video/*",
          capture: "camcorder",
          text: "录像",
        },
        {
          type: "button",
          name: "yuyin",
          icon: require('../static/pic/yuyintonghua.png'),
          text: "语音通话",
        },
        {
          type: "button",
          name: "shipin",
          icon: require('../static/pic/shipintonghua.png'),
          text: "视频通话",
        },
        {
          type: "button",
          name: "hongbao",
          icon: require('../static/pic/hongbao.png'),
          text: "红包",
        },
        {
          type: "file",
          icon: require('../static/pic/fujian.png'),
          text: "附件",
        },
      ],
    };
  },
  //方法集合
  methods: {
    // 内容改变的时候进行样式的控制
    contentChange (e) {
      var content = this.$refs.chatContentDom.innerHTML;

      if (content) {
        this.chatContent = content;
      } else {
        this.chatContent = "";
      }
    },
    promiseSetText () {
      var that = this;
      return new Promise((resolve, reject) => {
        that.isText = !that.isText;
        return resolve();
      });
    },
    promiseSetFocus () {
      var that = this;
      return new Promise((resolve, reject) => {
        that.$refs.chatContentDom.focus();

        return resolve();
      });
    },
    promiseSetBlur () {
      var that = this;
      return new Promise((resolve, reject) => {
        that.$refs.chatContentDom.blur();
        return resolve();
      });
    },
    // 切换文本输入和语音输入
    toggle () {

      // 如果是显示文本输入则将之前保存的光标位置重新赋值给文本框
      if (!this.isText) {
        this.setDivCursorPosition(this.$refs.chatContentDom, this.cursor);
      }
      // 如果有键盘/其他弹框将其恢复
      var currentStickyDom = document.querySelector("#stickyBottom");
      var stickyParentDom = currentStickyDom.firstChild;
      var that = this;
      that
        .promiseSetText()
        .then((data) => {
          that.showCamera = false;
          currentStickyDom.style.height = "2.00038rem";
          stickyParentDom.style.height = "2.00038rem";
          that.promiseSetFocus();
          that.$emitter.emit('changeChatContentHeight', { "chatHeight": "15.35rem", });

        })
        .catch((err) => {
          // 抛出错误信息
          console.log(err);
        });
    },

    // 手指开始触发
    touchstart (e) {
      // 组织长按浏览器弹框默认行为
      e.preventDefault();

      this.recordPeriodTime = 0;
      this.blackBoxSpeak = true;
      this.startY = e.touches[0].clientY;
      // 每1秒打印一次(无实质用途)
      this.loop = setInterval(() => {
        this.recordPeriodTime++;
        if (this.recordPeriodTime >= 60) {
          this.endEarly = true;
          this.touchend();
        }
      }, 1000);
      // 长按1000毫秒后执行
      this.delayTime = setTimeout(() => {
        this.startRecord();
      }, 1000);
      return false;
    },
    // 长按超过1000毫秒
    startRecord () {
      // 展示录音图标
      this.btRecoding = true;
      // =========================================调用录音方法,webrtc==================================================
      if (this.recorder !== null) {
        this.recorder.close()
      }
      Recorder.get((rec) => {
        this.recorder = rec
        this.recorder.start()
      })
    },
    // 短按
    startRecordClick () {
      // 长按没有超过1000毫秒
      console.log("长按没有超过1000毫秒");
    },
    // 手指离开屏幕触发, 最大只能录制60秒
    touchend () {
      if (this.endEarly) {
        this.endEarly = false;
        return;
      }
      clearTimeout(this.loop);
      clearTimeout(this.delayTime);
      if (this.recordPeriodTime < 1) {
        this.startRecordClick();
      } else {
        this.btRecoding = false;
        // 长按结束调用保存录音或者其实事件
        // 判断是否取消了录音，如果没有取消则进行发送上传；
        //调用录音停止和关闭方法
        if (!this.recorder) {
          alert("不支持发送语音！")
          return;
        }
        var recordBlob = this.recorder.getBlob();
        // 关闭麦克风
        this.recorder.close();
        //如果未取消录音则上传录音数据
        if (this.blackBoxSpeak) {
          // 异步处理
          this.handleYuyin(recordBlob);
        }
      }
      // 重新设置开始至
      this.recorder = null;
      this.loop = "";
      this.delayTime = "";
      this.startY = 0;
      this.recordPeriodTime = 0;
      this.btRecoding = false;
      this.blackBoxSpeak = false;
    },
    // 滑动触发
    touchmove (e) {
      const endY = e.touches[0].clientY;
      if (this.startY - 30 < endY) {
        this.blackBoxSpeak = true;
      } else {
        this.blackBoxSpeak = false;
      }
    },







    //点击加号进行展示
    toggleShowCameraPopup () {
      this.showEmoji = false;
      // 获取吸顶元素dom 以及父元素dom
      var currentStickyDom = document.querySelector("#stickyBottom");
      var stickyParentDom = currentStickyDom.firstChild;

      setTimeout(() => {
        // 重置为输入框
        this.isText = true;
        if (this.showCamera) {
          currentStickyDom.style.height = "2.00038rem";
          stickyParentDom.style.height = "2.00038rem";
          this.$emitter.emit('changeChatContentHeight', { "chatHeight": "15.35rem", });
        } else {
          // 展示吸顶层
          currentStickyDom.style.height = "9.72rem";
          stickyParentDom.style.height = "9.72rem";
          this.$emitter.emit('changeChatContentHeight', { "chatHeight": "7.6rem", });

        }
        this.showCamera = !this.showCamera;

      }, 10);
    },
    // 失去焦点收起键盘，blur
    withdrawKeyBoard () {
      // 将当前失去焦点后的光标位置存起来
      this.cursor = this.getDivCursorPosition(this.$refs.chatContentDom);


      // 获取当前激活的dom
      console.log("失去焦点后光标位置" + this.cursor);
    },
    // 获取焦点弹出键盘, fouse
    popKeyBoard () {
      console.log("获取焦点");
      if (this.showCamera) {
        // 失去焦点隐藏键盘
        this.$refs.chatContentDom.blur();
      }

    },

    // 在可编辑框内插入html,根据isCursorChange参数来判断光标是否改变 true-光标改变为插入文本后的光标，false-还是文本插入之前的光标
    insertHtmltoDiv (html, isCursorChange) {
      var divInput = this.$refs.chatContentDom;
      if (this.chatContent) {
        divInput.innerHTML = this.chatContent.substring(0, this.cursor) + html + this.chatContent.substring(this.cursor)
      } else {
        divInput.innerHTML = html;
      }

      // 给添加后的内容重新赋值
      this.chatContent = divInput.innerHTML;
      if (isCursorChange) {
        this.cursor = html.length + this.cursor;
        this.setDivCursorPosition(divInput, this.cursor);
      }
    },
    //获取div当前光标位置
    getDivCursorPosition (element) {
      var caretOffset = 0;
      var doc = element.ownerDocument || element.document;
      var win = doc.defaultView || doc.parentWindow;
      var sel;
      if (typeof win.getSelection != "undefined") {//谷歌、火狐
        sel = win.getSelection();
        if (sel.rangeCount > 0) {//选中的区域
          var range = win.getSelection().getRangeAt(0);
          var preCaretRange = range.cloneRange();//克隆一个选中区域
          preCaretRange.selectNodeContents(element);//设置选中区域的节点内容为当前节点
          preCaretRange.setEnd(range.endContainer, range.endOffset);  //重置选中区域的结束位置
          caretOffset = preCaretRange.toString().length;
        }
      } else if ((sel = doc.selection) && sel.type != "Control") {//IE
        var textRange = sel.createRange();
        var preCaretTextRange = doc.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
      }
      return caretOffset;
    },
    //设置光标位置
    setDivCursorPosition (element, pos) {
      var range, selection;
      if (document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
      {
        range = document.createRange();//创建一个选中区域
        range.selectNodeContents(element);//选中节点的内容
        if (element.innerHTML.length > 0) {
          range.setStart(element.childNodes[0], pos); //设置光标起始为指定位置
        }
        range.collapse(true);       //设置选中区域为一个点
        selection = window.getSelection();//获取当前选中区域
        selection.removeAllRanges();//移出所有的选中范围
        selection.addRange(range);//添加新建的范围
      }
      else if (document.selection)//IE 8 and lower
      {
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(element);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
      }
    },

    // 展示表情弹框
    toggleShowEmoji () {
      return;
      // this.showEmoji = true;
      // // 获取吸顶元素dom 以及父元素dom
      // var currentStickyDom = document.querySelector("#stickyBottom");
      // var stickyParentDom = currentStickyDom.firstChild;

      // setTimeout(() => {
      //   // 重置为输入框
      //   this.isText = true;
      //   if (this.showCamera) {
      //     currentStickyDom.style.height = "2.00038rem";
      //     stickyParentDom.style.height = "2.00038rem";
      //   } else {
      //     // 展示吸顶层
      //     currentStickyDom.style.height = "9.72rem";
      //     stickyParentDom.style.height = "9.72rem";
      //   }
      //   this.showCamera = !this.showCamera;

      // }, 10);


    },


    // 发送消息
    sendChatMsg () {

      if (this.chatContent === '' || this.chatContent === undefined) {
        return
      }
      // 给对方发送通知，自己添加成功的请求
      const socket = this.$store.state.socket;
      if (socket) {
        // 封装添加好友的消息类型
        let pChatMessage = new proto.com.ouyu.im.Message();
        pChatMessage.setFrom(this.$socket.config.identity)
        pChatMessage.setTo(this.to)
        pChatMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT);
        pChatMessage.setContent(this.chatContent);
        // 时间戳毫秒
        pChatMessage.setCreateTime(new Date().getTime());
        var msgId = socket.send(pChatMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_P_CHAT);
        var divInput = this.$refs.chatContentDom;
        divInput.innerHTML = '';
        var temContent = this.chatContent;
        this.chatContent = '';

        // 集合中追加一条数据
        this.$emit("sendMsg", { "chatContent": temContent, "msgId": msgId, "contentType": SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT });
      } else {
        Toast.fail("无效连接！")
      }
    },

    // 处理语音这里的数据是wav 文件的blob
    handleYuyin (yuyinBlob) {
      new Promise((resolve, reject) => {
        //在这里异步处理数据
        var formData = new FormData();
        formData.append("fileType", "1");
        formData.append("files", yuyinBlob, "ouyunc_yuyin.wav");
        var that = this;
        // 调用接口提交数据
        this.$http
          .post_form(this.$reqPrefix.im + "/im/file/upload", formData, null).then(res => {
            // 异步
            const socket = that.$store.state.socket;
            if (socket) {
              // 封装添加好友的消息类型
              let pChatMessage = new proto.com.ouyu.im.Message();
              pChatMessage.setFrom(that.$socket.config.identity)
              pChatMessage.setTo(that.to)
              pChatMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.ATTACHMENT_CONTENT);
              pChatMessage.setContent(JSON.stringify(res.data));
              // 时间戳毫秒
              pChatMessage.setCreateTime(new Date().getTime());
              var msgId = socket.send(pChatMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_P_CHAT);
              // 集合中追加一条数据
              that.$emit("sendMsg", { "chatContent": res.data, "msgId": msgId, "contentType": SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.ATTACHMENT_CONTENT });
              resolve("success");
            } else {
              Toast.fail("无效连接！")
            }
          }).catch(err => {
            Toast.fail(err.data.message)
          });
      }).then(res => {
        // 这里拿到的是resolve() 方法的参数；在这里进行数据的追加和渲染
        console.log(res)

      }).catch(err => {

      });
      console.log("开始处理blob");
    },

    // 上传文件：图片/视频/附件...
    uploadFile (e) {
      var files = e.target.files;
      if (files.length <= 0) {
        return;
      }
      // 构建入参数据
      var formData = new FormData();
      files.forEach(file => {
        // 注意这里files 所代表的key 对应后台的入参名称，以数组的形式接收
        formData.append("files", file);
        formData.append("fileType", "9");

      });
      var that = this;
      // 调用接口提交数据
      this.$http
        .post_form(this.$reqPrefix.im + "/im/file/upload", formData, null).then(res => {
          // 异步
          const socket = that.$store.state.socket;
          if (socket) {
            // 封装添加好友的消息类型
            let pChatMessage = new proto.com.ouyu.im.Message();
            pChatMessage.setFrom(that.$socket.config.identity)
            pChatMessage.setTo(that.to)
            pChatMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.ATTACHMENT_CONTENT);
            pChatMessage.setContent(JSON.stringify(res.data));
            // 时间戳毫秒
            pChatMessage.setCreateTime(new Date().getTime());
            var msgId = socket.send(pChatMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.IM_P_CHAT);
            // 集合中追加一条数据
            that.$emit("sendMsg", { "chatContent": res.data, "msgId": msgId, "contentType": SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.ATTACHMENT_CONTENT });
          } else {
            Toast.fail("无效连接！")
          }
        }).catch(err => {
          Toast.fail(err.data.message)
        });


    },
    // 调用语音通话
    callYuyin () {

      var that = this;
      const socket = that.$store.state.socket;
      var config = {
        type: 'yuyin-call',
        constraints: {
          audio: true,
          //video: true
        },
        from: this.$socket.config.identity,
        to: this.to
      }

      // 初始化webrtc
      Webrtc.init(socket).call(config, (webrtc) => {
        this.showOverlay = true;
        // 将webrtc 存起来
        this.$store.commit('setWebrtc', webrtc);
        // 最多等候15秒，如果对方不在线或没处理则会自动结束
        let timeObj = setTimeout(() => {
          that.isCaller = true;
          that.showOverlay = false;
          // 释放资源
          if (webrtc) {
            webrtc.releaseSource();
            this.$store.commit('setWebrtc', null);
          }
        }, 15 * 1000);
        that.$store.commit('setMaxDelayReceiveTime', timeObj)
      }, (localMediaStream, remoteMediaStream) => {
        var remoteVideoDom = document.querySelector("#othersAudio");
        remoteVideoDom.srcObject = remoteMediaStream[0];
      });
    },

    //接听语音通话
    answering () {

      const socket = this.$store.state.socket;
      var webrtcConfig = {
        type: 'yuyin-call',
        constraints: {
          audio: true,
          //video: true
        },
        from: this.$socket.config.identity,
        to: this.to
      }
      // 接收方准备接收发起方的请求
      Webrtc.init(socket).receive(webrtcConfig, (webrtc) => {
        // 将webrtc 存起来
        this.$store.commit('setWebrtc', webrtc);
        // 发送给发起方信令告知这边已经准备可以进行下一步
        let agreeCallMessage = new proto.com.ouyu.im.Message();
        agreeCallMessage.setFrom(webrtcConfig.from)
        agreeCallMessage.setTo(webrtcConfig.to)
        agreeCallMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT);
        agreeCallMessage.setContent(JSON.stringify({
          type: "agree-call",
        }));
        agreeCallMessage.setCreateTime(new Date().getTime());
        socket.send(agreeCallMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.WEBRTC_SIGNALING);
        // 取消延时执行的函数（关闭遮罩层）
        let maxDelayReceiveTime = this.$store.state.maxDelayReceiveTime;
        clearTimeout(maxDelayReceiveTime);

      }, (localMediaStream, remoteMediaStream) => {
        console.log("回调流信息", remoteMediaStream)
        var remoteAudioDom = document.querySelector("#othersAudio");
        remoteAudioDom.srcObject = remoteMediaStream[0];
        this.isCaller = true;

      });
    },
    // 拒接/挂断
    hungup () {
      const socket = this.$store.state.socket;
      var webrtc = this.$store.state.webrtc;

      // 发送一条挂断消息给对方
      let bayeMessage = new proto.com.ouyu.im.Message();
      bayeMessage.setFrom(this.$socket.config.identity)
      bayeMessage.setTo(this.to)
      bayeMessage.setContentType(SOCKET_CONSTANT.PACKET.MESSAGE_CONTENT_TYPE.TEXT_CONTENT);
      bayeMessage.setContent(JSON.stringify({
        type: "hungup",
      }));
      bayeMessage.setCreateTime(new Date().getTime());
      socket.send(bayeMessage, SOCKET_CONSTANT.PACKET.MESSAGE_TYPE.WEBRTC_SIGNALING);

      this.isCaller = true;
      this.showOverlay = false;

      // 释放资源
      if (webrtc) {
        webrtc.releaseSource();
        this.$store.commit('setWebrtc', null);
      }
    },
    // 视频通话
    callShipin () {
      console.log("视频")
      this.$router.replace({ name: "P2PVideo", params: { identity: this.to } });
      //this.showShipinOverlay = true;
    },
    // 红包
    callHongbao () {
      console.log("红包")
    },
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    var that = this;
    if (that.singleType === 'yuyin-call') {

      that.isCaller = false;
      that.showOverlay = true;
      // 如果15 秒没有接通回应就会关闭

      let timeObj = setTimeout(() => {
        var webrtc = that.$store.state.webrtc;

        that.isCaller = true;
        that.showOverlay = false;
        if (webrtc) {
          webrtc.releaseSource();
          this.$store.commit('setWebrtc', null);
        }
      }, 15 * 1000);
      that.$store.commit('setMaxDelayReceiveTime', timeObj)
    }
    if (that.singleType === 'hungup') {
      var webrtc = that.$store.state.webrtc;
      that.isCaller = true;
      that.showOverlay = false;
      if (webrtc) {
        webrtc.releaseSource();
        this.$store.commit('setWebrtc', null);
      }
    }
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },

  //生命周期 - 创建之前
  beforeCreate () { },
  //生命周期 - 挂载之前
  beforeMount () { },
  //生命周期 - 更新之前
  beforeUpdate () { },
  //生命周期 - 更新之后
  updated () { },
  //生命周期 - 销毁之前
  beforeUnmount () { },
  //生命周期 - 销毁完成
  unmounted () {
    clearTimeout(this.loop);
    clearTimeout(this.delayTime);
  },
  //如果页面有keep-alive缓存功能，这个函数会触发
  activated () { },
};
</script>
<style lang="less" scoped>
//@import url(); 引入公共css类
.chat-editor-container {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  justify-content: space-around;
  align-items: center;
  background-color: rgb(245, 245, 245);
  padding: 10px 0px 10px 0px;
  border-top: 1px solid #ebedf0;
}
.base {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-around;
  align-items: center;
  background-color: rgb(245, 245, 245);
  padding: 10px 0px 10px 0px;
}
.textarea,
select:focus {
  font-size: 15px;
  height: 25px;
  padding: 4px;
  width: 236px;
  border: 1px solid rgb(255, 255, 255);
  background-color: rgb(255, 255, 255);
  resize: vertical;
  overflow: auto;
  outline: none;
}

.textarea:empty:before {
  content: attr(placeholder);
  color: #bbb;
}
.left-icon {
  margin-right: 10px;
  margin-left: 10px;
}
.content-text {
}
.right-icon {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-around;
  align-items: center;
}
.right-icon-emoij {
  margin-left: 10px;
  margin-right: 10px;
}
.right-icon-add {
  margin-right: 10px;
}
.right-icon-add-none {
  margin-right: 12px;
}
.div-button-style {
  width: 200px;
}
.send-btn {
  width: 62px;
}
.record-btn {
  font-size: 15px;
  height: 35px;
  padding: 4px;
  width: 245px;
  border: 1px solid rgb(255, 255, 255);
  background-color: rgb(255, 255, 255);
  // 长按禁止选中文字
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.shade {
  z-index: 998;
  position: fixed;
  top: 5rem;
  width: 5rem;
  height: 5rem;
  img {
    width: 1.4rem;
    height: 2.3rem;
  }
  .blackBoxSpeak,
  .blackBoxPause {
    width: 2.8rem;
    height: 2.8rem;
    border-radius: 0.4rem;
    background-color: rgba(#000000, 0.7);
    margin: auto;
    padding: 0.4rem;
    text-align: center;
  }
  .blackBoxSpeakConent {
    color: rgb(255, 255, 255);
    text-align: center;
    font-size: 0.26rem;
    padding: 5px 0;
    width: 2.8rem;
    margin: auto;
    border-radius: 6px;
  }
}
.cameraPopup {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
  align-content: flex-start;
  width: 100%;
  height: 289.5px;
  border-top: 1px solid #ebedf0;
  background-color: rgb(245, 245, 245);
  .grid-input-style {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    align-content: center;
    justify-content: center;
    align-items: center;
    width: 93px;
    height: 93px;
    margin: 20px 0px 0px 0px;
    .icon-input {
      border-radius: 15px;
      width: 70%;
      height: 70%;
      // 替换具体的图标
      background-color: rgb(255, 255, 255);
      background-repeat: no-repeat;
      background-position: 50% 50%; /*这个是按从左往右，从上往下的百分比位置进行调整*/
      background-size: 50% 50%; /*按比例缩放*/
    }
    .icon-text {
      margin-top: 3px;
      color: gray;
      font-size: 12px;
    }
    .input-btn-style {
      width: 100%;
      height: 100%;
      opacity: 0;
    }
  }
}
.emojiPopup {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;
  align-content: flex-start;
  width: 100%;
  height: 289.5px;
  border-top: 1px solid #ebedf0;
  background-color: rgb(245, 245, 245);
}
.yuyin-container /deep/ .van-overlay {
  background-image: linear-gradient(to bottom right, #646566, black);
}
.yuyin-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: column;
  flex-wrap: nowrap;
  align-content: flex-start;
  height: 100%;
  .yuyin-head {
    width: 100%;
    line-height: 60px;
    text-align: center;
    color: #fff;
  }
  .yuyin-body {
    width: 3.2rem;
    height: 5rem;
    text-align: center;
    color: #fff;

    .user-avater-style {
    }
    .user-name-style {
      margin-top: 5px;
    }
  }
  .yuyin-foot {
    display: flex;
    flex-wrap: nowrap;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    width: 100%;
    height: 8rem;

    .maikefeng {
      text-align: center;
      width: 65px;
      line-height: 60px;
      border-radius: 50%;
      background-color: #fff;
    }
    .dianhua {
      text-align: center;
      width: 65px;
      line-height: 60px;
      border-radius: 50%;
      background-color: #fff;
    }
    .yangshengqi {
      text-align: center;
      width: 65px;
      line-height: 60px;
      border-radius: 50%;
      background-color: #fff;
    }
  }
}
</style>
